unit Work_With_Config_Unit;
interface
uses
    SysUtils, Classes, SyncObjs;

    type
        TConfig = class(TObject)
            private
                CS:TCriticalSection;
                FST:TStringList;
                constructor ActualCreate;

            public
                procedure Read(const FileName:String; out st:TStringList);
                procedure Write(const FileName:String; var st:TStringList);
                destructor Free;
                constructor Create;
                class function GetInstance: Tconfig;
                procedure ReleaseInstance;
        end;

var
    Ref_Count:Word=0;
    Instance: TConfig;
    
implementation

constructor TConfig.ActualCreate;
begin
    CS :=TCriticalSection.Create;
    FST:=TStringList.Create;
    Inherited;
end;

constructor TConfig.Create;
begin
    raise Exception.Create('Attempt to create an instance of Tconfig')
end;

class function TConfig.GetInstance: Tconfig;
begin
    if (Instance = nil) then
    begin
        Instance := Tconfig.ActualCreate;
    end;
    Inc(Ref_Count);
    Result := Instance;
end;

procedure TConfig.Read(const FileName:String; out st:TStringList);
begin
    CS.Enter;
    try
        if fileExists(FileName) then
        begin
            FST.Clear;
            FST.LoadFromFile(FileName);
            ST.Clear;
            ST.Assign(FST);
        end
        else
        begin
            FST.Clear;
            Write(FileName, FST);
            Read(FileName, st);
        end;
    finally
        CS.Leave;
    end;
end;
procedure TConfig.Write(const FileName:String; var st:TStringList);
begin
    CS.Enter;
    try
        FST.Clear;
        FST.Assign(ST);
        FST.SaveToFile(FileName);
    finally
        CS.Leave;
    end;
end;

destructor TConfig.Free;
begin
    FST.Free;
    CS.Free;
    Instance:=nil;
end;

procedure TConfig.ReleaseInstance;
begin
    Dec(Ref_Count);
    if (Ref_Count=0) then
    begin
        Free;
    end;
end;

end.
 